import { login as _login, getUserInfo as _getUserInfo, logout as _logout } from '@/api/login'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { IUserInfoVo } from '@/api/login.typings'

// 初始化状态
const userInfoState: IUserInfoVo = {
  userId: 0,
  nickName: '游戏玩家12345',
  accountGrade: '1',
  blueBlock: 0,
  bluePiece: 0,
  redBlock: 0,
  redPiece: 0,
  yellowBlock: 0,
  yellowPiece: 0,
  hasNotice: false,
  idAuthentication: false,
  avatar: '/static/images/default-avatar.png',
  token: '',
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 定义用户信息
    const userInfo = ref<IUserInfoVo>({ ...userInfoState })
    // 设置用户信息
    const setUserInfo = (val: IUserInfoVo) => {
      // console.log('设置用户信息', val)
      // // 若头像为空 则使用默认头像
      // if (!val.avatar) {
      //   val.avatar = userInfoState.avatar
      // } else {
      //   val.avatar = 'https://oss.laf.run/ukw0y1-site/avatar.jpg?feige'
      // }
      // if (!val.roles) {
      //   val.roles = userInfoState.roles
      // }
      userInfo.value = val
    }
    // 删除用户信息
    const removeUserInfo = () => {
      userInfo.value = { ...userInfoState }
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
    }
    /**
     * 用户登录
     * @param credentials 登录参数
     * @returns R<IUserLogin>
     */
    const login = async (credentials: { mobilePhone: number; checkNumber: number }) => {
      const res = await _login(credentials)
      return res
    }
    /**
     * 获取用户信息
     */
    const getUserInfo = async () => {
      const res = await _getUserInfo()
      const info = res.data
      if (info && typeof info === 'object') {
        setUserInfo(info as IUserInfoVo)
      } else {
        setUserInfo({ ...userInfoState })
      }
      uni.setStorageSync('userInfo', info)
      // TODO 这里可以增加获取用户路由的方法 根据用户的角色动态生成路由
      return info
    }
    /**
     * 退出登录 并 删除用户信息
     */
    const logout = async () => {
      // _logout()
      removeUserInfo()
      uni.reLaunch({ url: '/pages/login/index' })
    }

    return {
      userInfo,
      login,
      getUserInfo,
      logout,
    }
  },
  {
    persist: true,
  },
)
